let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabFirstList: [],
    selectFirstIndex:0,
    navActive:0,//导航栏选中id
    heightArr: [],
    containerH: 0,
  },
  ready() {
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getFirstTabs();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  //获取tab
  getFirstTabs(){
    let _this = this;
    let user = app.getUser();
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/category',
      data: {
        parentid: 0,
        type:4,
        centreId: app.globalData.loginCentreId
      }
    }).then((res)=>{
      let list = _this.makeTree(res.data.data);
      _this.setData({
        tabFirstList: list
      });
    })
  },
  //处理tab数据
  makeTree(data){
    let tree = {};
    data.forEach(item => {
      if (item.enabled &&  (item.status === 1)) {
        tree[item.id] = item;
      }
    });

    data.forEach(item => {
      if (item.enabled &&  (item.status === 1) && (item.parentid > 0)) {
        let parent = tree[item.parentid];

        if (parent) {
          if (!parent.children) {
            parent.children = [];
          }
          parent.children.push(item);
        }
      }
    });

    return data.filter(item => (item.parentid === 0) && ((item.enabled &&  (item.status === 1))));
  },
  selectFirstTab:function(e){
    let that = this;
    let id = e.currentTarget.dataset.id;
    console.log(id);
    let index = e.currentTarget.dataset.index;
    that.setData({
      selectFirstIndex:e.currentTarget.dataset.index,
      contentActive: id,
      navActive: index
    });
  },
  onScroll(e) {
    let query = wx.createSelectorQuery().in(this);
    let heightArr = [];
    let s = 0;
    query.selectAll('.pesticide').boundingClientRect((react) => {
      react.forEach((res) => {
        s += res.height;
        heightArr.push(s)
      });
      this.setData({
        heightArr: heightArr
      })
    });
    query.select('.content').boundingClientRect((res) => {
      // 计算容器高度
      this.setData({
        containerH: res.height
      })
    }).exec();
    let scrollTop = e.detail.scrollTop;
    let scrollArr = this.data.heightArr;
    if (scrollTop >= scrollArr[scrollArr.length - 1] - this.data.containerH) {
      return
    } else {
      for (let i = 0; i < scrollArr.length; i++) {
        if (scrollTop >= 0 && scrollTop < scrollArr[0]) {
          this.setData({
            navActive: 0
          })
        } else if (scrollTop >= scrollArr[i - 1] && scrollTop < scrollArr[i]) {
          this.setData({
            navActive: i
          })
        }
      }
    }
  },
  // 跳转搜索列表
  toSearch:function(){
    wx.navigateTo({
      url: '/pages/index/search/search?type=0'
    })
  },
  //跳转商品列表
  jumpGoodsList:function(e){
    wx.navigateTo({
      url: '/pages/classify/goodsList/goodsList?categoryId='+e.currentTarget.dataset.id
    })
  },
})